package org.jeecg.modules.demo.commoditygroup.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.commoditygroup.entity.CommodityGroup;
import org.jeecg.modules.demo.commoditygroup.service.ICommodityGroupService;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityManagement;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 商品分组
 */
@Api(tags = "商品分组")
@RestController
@RequestMapping("/commoditygroup/commodityGroup")
@Slf4j
public class CommodityGroupController extends JeecgController<CommodityGroup, ICommodityGroupService> {
    @Autowired
    private ICommodityGroupService commodityGroupService;
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "商品分组-分页列表查询")
    @ApiOperation(value = "商品分组-分页列表查询", notes = "商品分组-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CommodityGroup commodityGroup,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<CommodityGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId).orderByAsc("weight");
        QueryGenerator.initQueryWrapper(queryWrapper, commodityGroup, req.getParameterMap());
        Page<CommodityGroup> page = new Page<CommodityGroup>(pageNo, pageSize);
        IPage<CommodityGroup> pageList = commodityGroupService.page(page, queryWrapper);

        List<CommodityGroup> listMap = pageList.getRecords();
        listMap.forEach(cg -> {
            int count = commodityManagementService.count(new QueryWrapper<CommodityManagement>()
                    .eq("group_id", cg.getId())
                    .eq("store_id", storeId));
            cg.setGoodsNum(count);
        });

        // 从大到小排序
/*        listMap.sort((o1, o2) -> {
            if (o1.equals(o2)) {
                return 0;
            } else if (Integer.parseInt(o1.getWeight()) > Integer.parseInt(o2.getWeight())) {
                //o2为前值，o1为后值；这里理解为：后值比前值大，则不交换位置,等价从小到大排序
                //如果这里返回 -1，则为从大到小排序
                return -1;
            } else {
                //后值比前值小，则交换位置
                return 1;
            }
        });
        */
        return Result.OK(listMap);
    }

    /**
     * 根据店铺id查询商品分组列表（用于库存新增时添加商品）
     */
    @GetMapping(value = "/getGroupList")
    public Result<?> getListByStoreId(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<CommodityGroup> list = commodityGroupService.getListByStoreId(storeId);
        return Result.OK(list);
    }

    /**
     * 根据groupId查询商品分组列表（用于入库时添加商品，查该分组的所有商品）
     */
    @GetMapping(value = "/getCommodityListByGroup")
    public Result<?> getCommodityListByGroup(String groupId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<CommodityManagement> list = commodityManagementService.list(new QueryWrapper<CommodityManagement>()
                .eq("group_id", groupId)
                .eq("store_id", storeId));
        return Result.OK(list);
    }

    /**
     * 根据groupId查询商品分组列表（用于出库时添加商品，查该分组库存不为0的商品）
     */
    @GetMapping(value = "/getCommodityListByGroupOut")
    public Result<?> getCommodityListByGroupOut(String groupId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<CommodityManagement> list = commodityManagementService.list(new QueryWrapper<CommodityManagement>()
                .eq("group_id", groupId)
                .eq("store_id", storeId)
                .ne("inventory", 0));
        return Result.OK(list);
    }

    /**
     * 添加
     */
    @AutoLog(value = "商品分组-添加")
    @ApiOperation(value = "商品分组-添加", notes = "商品分组-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CommodityGroup commodityGroup, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        commodityGroup.setStoreId(storeId);
        // 当前店铺全部商品分组
        List<CommodityGroup> list = commodityGroupService.list(new QueryWrapper<CommodityGroup>().eq("store_id", storeId));
        // list中与commodityGroup同名的商品分组个数
        long count = list.stream().filter(cg -> cg.getGroupName().equals(commodityGroup.getGroupName())).count();
        if (count > 0) {
            return Result.error("添加失败，该店铺已有同名商品分组！");
        }
        if (commodityGroup.getGrossRate() == null) {
            commodityGroup.setGrossRate(0.00);
        }
        if (commodityGroup.getGrossRate() < 0 || commodityGroup.getGrossRate() > 100) {
            return Result.error("添加失败，毛利率应在0-100范围内！");
        }
        commodityGroupService.save(commodityGroup);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     */
    @AutoLog(value = "商品分组-编辑")
    @ApiOperation(value = "商品分组-编辑", notes = "商品分组-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CommodityGroup commodityGroup, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        // 当前店铺全部商品分组
        List<CommodityGroup> list = commodityGroupService.list(new QueryWrapper<CommodityGroup>()
                .eq("store_id", storeId)
                .ne("id", commodityGroup.getId()));
        // list中与commodityGroup同名的商品分组个数
        long count = list.stream().filter(cg -> cg.getGroupName().equals(commodityGroup.getGroupName())).count();
        if (count > 0) {
            return Result.error("编辑失败，该店铺已有同名商品分组！");
        }
        if (commodityGroup.getGrossRate() != null && (commodityGroup.getGrossRate() < 0 || commodityGroup.getGrossRate() > 100)) {
            return Result.error("编辑失败，毛利率应在0-100范围内！");
        }
        commodityGroupService.updateById(commodityGroup);
        // 更新商品表中的商品分组名称
        commodityManagementService.updateGroupName(commodityGroup.getGroupName(), commodityGroup.getId());
        return Result.OK("编辑成功！");
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "商品分组-通过id删除")
    @ApiOperation(value = "商品分组-通过id删除", notes = "商品分组-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> delete(@RequestParam("id") String id) {
        commodityGroupService.removeById(id);
        // 删除商品分组时，将关联的商品的商品分组属性清空
        CommodityManagement cm = new CommodityManagement();
        cm.setGroupId("");
        cm.setClassificationGoods("");
        commodityManagementService.update(cm, new QueryWrapper<CommodityManagement>().eq("group_id", id));
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "商品分组-批量删除")
    @ApiOperation(value = "商品分组-批量删除", notes = "商品分组-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(@RequestParam("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        this.commodityGroupService.removeByIds(idList);
        // 删除商品分组时，将关联的商品的商品分组属性清空
        CommodityManagement cm = new CommodityManagement();
        cm.setGroupId("");
        cm.setClassificationGoods("");
        commodityManagementService.update(cm, new QueryWrapper<CommodityManagement>().in("group_id", idList));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "商品分组-通过id查询")
    @ApiOperation(value = "商品分组-通过id查询", notes = "商品分组-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CommodityGroup commodityGroup = commodityGroupService.getById(id);
        if (commodityGroup == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(commodityGroup);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CommodityGroup commodityGroup) {
        return super.exportXls(request, commodityGroup, CommodityGroup.class, "商品分组");
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CommodityGroup.class);
    }

}
